package roleservicelogic

import (
	"context"
	"database/sql"
	"time"

	"smile-sunshine-micorservice/rpc/User/db/crud"
	"smile-sunshine-micorservice/rpc/User/internal/svc"
	"smile-sunshine-micorservice/rpc/User/pb/zipTako.com/SmileSunshine/user"

	"github.com/zeromicro/go-zero/core/logx"
)

type DeleteRoleLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
	RolesModel crud.RolesModel
}

func NewDeleteRoleLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DeleteRoleLogic {
	return &DeleteRoleLogic{
		ctx:        ctx,
		svcCtx:     svcCtx,
		Logger:     logx.WithContext(ctx),
		RolesModel: crud.NewRolesModel(svcCtx.SqlConn, svcCtx.CacheConf),
	}
}

func (l *DeleteRoleLogic) DeleteRole(in *user.DeleteRoleRequest) (*user.DeleteRoleResponse, error) {
	l.Logger.Infof("收到删除角色请求，角色ID：%d", in.Id)

	// 1. 检查角色是否存在
	role, err := l.RolesModel.FindOne(l.ctx, in.Id)
	if err != nil {
		return &user.DeleteRoleResponse{
			Success: false,
			Message: "角色不存在",
		}, nil
	}

	// 2. 检查角色是否已被删除
	if role.DeletedAt.Valid == true {
		return &user.DeleteRoleResponse{
			Success: false,
			Message: "角色已被删除",
		}, nil
	}

	// 3. 检查是否为系统预设角色（比如admin）
	if role.Name == "admin" {
		return &user.DeleteRoleResponse{
			Success: false,
			Message: "系统预设角色不能删除",
		}, nil
	}

	// 4. 执行软删除
	now := time.Now()
	role.DeletedAt = sql.NullTime{
		Time:  now,
		Valid: true,
	}

	err = l.RolesModel.Update(l.ctx, role)
	if err != nil {
		l.Logger.Errorf("删除角色失败：%v", err)
		return &user.DeleteRoleResponse{
			Success: false,
			Message: "删除角色失败，请稍后重试",
		}, nil
	}

	// 5. 返回成功响应
	return &user.DeleteRoleResponse{
		Success: true,
		Message: "删除角色成功",
	}, nil
}
